package cn.tedu.server;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

@Component
public class CharServer {
    private ServerSocket serverSocket;
    @Value("8080")
    void server(int port) {
        try {
            this.serverSocket = new ServerSocket(port);
            System.out.println("服务器启动成功...");
            try {
                System.out.println("等待客户端连接");
                while (true) {
                    Socket socket = serverSocket.accept();
                    System.out.println("有新客户端连接成功");
                    ClientHandler clientHandler = new ClientHandler(socket);
                    Thread thread = new Thread(clientHandler);
                    thread.start();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }finally {
            try {serverSocket.close();} catch (IOException e) {e.printStackTrace();}
        }
    }

    public static void main(String[] args) {
        ApplicationContext context = new
                AnnotationConfigApplicationContext(SpringConfig.class);
        CharServer charServer = context.getBean(CharServer.class);
        //charServer.start();
    }
}
